<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 两个数组的并集, 交集, 差集
      const arr1 = [1, 2, 4, 6];
      const arr2 = [3, 2, 4, 7];

      // 并集(拥有两个集合中的所有数据, 并且不允许出现重复项)
      const ret = [...new Set(arr1.concat(arr2))];
      console.log("并集", ret);

      // 交集(得到两个集合中同时存在的数据)
      const s2 = new Set(arr2);
      const cross = [...new Set(arr1)].filter((item) => s2.has(item));
      console.log("交集:", cross);

      // 差集
      const s1 = new Set(arr1);
      const ret2 = [...new Set(arr1.concat(arr2))].filter(
        (item) =>
          (s1.has(item) && !s2.has(item)) || (!s1.has(item) && s2.has(item))
      );
      const ret3 = [...new Set(arr1.concat(arr2))].filter(
        (item) => !cross.includes(item)
      );
      console.log(ret2, ret3);
    </script>
  </body>
</html>
